package Extra;

import EmailService.MyAuthenticator;
import EmailService.ReceiveInfo;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

import javax.mail.Folder;
import javax.mail.MessagingException;

import javax.mail.Session;
import java.util.Properties;

/**
 * 监听邮件线程
 * 继承Thread并且复写run方法
 */
public class ListenThread extends Thread {

    private ReceiveInfo info = null;

    public ListenThread(ReceiveInfo info){
        this.info = info;
    }

    /**
     * 重写run方法
     */
    @Override
    public void run() {

        try{
            Properties props = info.getProperties();


            MyAuthenticator authenticator = null;

            if(info.isValidate()){
                authenticator = new MyAuthenticator(info.getUserName(),
                        info.getUserPassword());
            }else{
                return;
            }

            Session session = Session.getInstance(props,authenticator);
            //session.setDebug(true);// 打印调试信息


            IMAPStore store = (IMAPStore) session.getStore("imap");
            store.connect();

            IMAPFolder folder = (IMAPFolder)store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);

            int number = folder.getNewMessageCount();

            while(number==0){
                number = folder.getNewMessageCount();
            }
            System.out.println("有一封新邮件");

        }catch (MessagingException e){
            e.printStackTrace();
        }



    }

}
